package org.hospital.service.impl;


import java.text.SimpleDateFormat;
import java.util.List;

import org.hospital.entity.Clinic;
import org.hospital.entity.ClinicDAO;
import org.hospital.entity.Employee;
import org.hospital.entity.EmployeeDAO;
import org.hospital.service.ClinicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class ClinicServiceImpl implements ClinicService {

	@Autowired
	private ClinicDAO cDao;
	@Autowired
	private EmployeeDAO eDao;

	@Override
	public Clinic getByid(int clinicId) {
		return cDao.findById(clinicId);
	}

	@Override
	public Clinic addEntity(Clinic entity) {
		return cDao.merge(entity);
	}

	@Override
	public Clinic saveEntity(Clinic entity) {
		return cDao.merge(entity);
	}

	@Override
	public JSONArray getAll() {
		List<Clinic> cList = cDao.findAll();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		JSONArray resultJA = new JSONArray();
		for (int i = 0; i < cList.size(); i++) {
			Clinic clinic = cList.get(i);
			
			JSONObject resultJO = new JSONObject();
			Employee creator = eDao.findById(clinic.getCreatorId());
			Employee principal =  eDao.findById(clinic.getEmployeeId());
			resultJO.put("clinicId", clinic.getClinicId());
			resultJO.put("clinicName", clinic.getName());
			resultJO.put("creatorId", clinic.getCreatorId());
			resultJO.put("creatorName", creator.getName());
			resultJO.put("creatorCode", creator.getEmployeeCode());
			resultJO.put("principalId", clinic.getEmployeeId());
			resultJO.put("principalName", principal.getName());
			resultJO.put("principalCode", principal.getEmployeeCode());
			resultJO.put("createTime", sdf.format(clinic.getCreateTime()));
			if(clinic.getAddress() == null) {
				resultJO.put("address", "");
			}else {
				resultJO.put("address", clinic.getAddress());
			}
			if(clinic.getPhone() == null) {
				resultJO.put("phone", "");
			}else {
				resultJO.put("phone", clinic.getPhone());
			}
			resultJA.add(resultJO);
		}
		
		return resultJA;
	}

}
